<template>
  <div class="register-container">
    <div class="register-card">
      <div class="register-header">
        <h2>注册账号</h2>
        <p class="subtitle">欢迎加入生鲜超市</p>
      </div>

      <form class="register-form" @submit.prevent="handleRegister">
        <div class="form-group">
          <label>用户名</label>
          <div class="input-wrapper">
            <el-icon><User /></el-icon>
            <input 
              type="text" 
              v-model="formData.username" 
              placeholder="请输入用户名"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <label>手机号</label>
          <div class="input-wrapper">
            <el-icon><Iphone /></el-icon>
            <input 
              type="tel" 
              v-model="formData.phone" 
              placeholder="请输入手机号"
              pattern="[0-9]{11}"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <label>性别</label>
          <div class="gender-options">
            <label class="gender-option">
              <input type="radio" v-model="formData.gender" :value="0" />
              <span>未知</span>
            </label>
            <label class="gender-option">
              <input type="radio" v-model="formData.gender" :value="1" />
              <span>男</span>
            </label>
            <label class="gender-option">
              <input type="radio" v-model="formData.gender" :value="2" />
              <span>女</span>
            </label>
          </div>
        </div>

        <div class="form-group">
          <label>头像</label>
          <div class="avatar-upload">
            <div class="avatar-preview" v-if="formData.img">
              <img :src="formData.img" alt="头像预览" />
              <div class="avatar-edit">
                <el-icon><User /></el-icon>
              </div>
            </div>
            <div class="avatar-placeholder" v-else>
              <el-icon><User /></el-icon>
            </div>
            <input 
              type="file" 
              accept="image/*" 
              @change="handleAvatarChange" 
              class="avatar-input"
            />
          </div>
        </div>

        <div class="form-group">
          <label>密码</label>
          <div class="input-wrapper">
            <el-icon><Lock /></el-icon>
            <input 
              :type="showPassword ? 'text' : 'password'" 
              v-model="formData.password" 
              placeholder="请输入密码"
              required
            />
            <el-icon 
              :class="showPassword ? 'el-icon-view' : 'el-icon-view'"
              @click="showPassword = !showPassword"
            ></el-icon>
          </div>
        </div>

        <button type="submit" class="register-btn" >
          立即注册
        </button>

        <div class="login-link">
          已有账号？<a href="#" @click.prevent="$router.push('/login')">立即登录</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { register } from '@/axios/auth'
import { ElMessage, ElLoading } from 'element-plus'
import { useRouter } from 'vue-router'
import { User, Iphone, Lock } from '@element-plus/icons-vue'
import axios from '@/axios/index'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const showPassword = ref(false)
const showConfirmPassword = ref(false)

const formData = reactive({
  username: '',
  password: '',
  phone: '',
  gender: 0,
  img: '',
})

const selectedFile = ref(null)

// 头像上传
const handleAvatarChange = async (e) => {
  const file = e.target.files[0] // 获取上传的文件
  if (!file) return

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请上传图片文件')
    return
  }
  
  // 验证文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '上传中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    // 创建 FormData
    const avatarFormData = new FormData()
    avatarFormData.append('file', file)

    // 调用注册上传头像接口
    const uploadRes = await axios.post('/user/upload/avatar/register', avatarFormData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (uploadRes.code === 1) {
      // 上传成功，保存头像URL到表单数据
      formData.img = uploadRes.data
      // 创建本地预览
      const previewUrl = URL.createObjectURL(file)
      document.querySelector('.avatar-preview img').src = previewUrl
      ElMessage.success('头像上传成功')
    } else {
      ElMessage.error(uploadRes.msg || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请重试')
  } finally {
    loading.close()
  }
}

// 登录方法
const login = async (username, password) => {
  try {
    const res = await axios.post('/user/login', {
      username,
      password
    })
    if (res.code === 1) {
      userStore.setToken(res.data.token)
      return true
    }
    return false
  } catch (error) {
    console.error('登录失败:', error)
    return false
  }
}

const handleRegister = async () => {
  try {
    // 表单验证
    if (!formData.username || !formData.password || !formData.phone) {
      ElMessage.warning('请填写完整信息')
      return
    }
    
    // 手机号格式验证
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      ElMessage.warning('请输入正确的手机号')
      return
    }

    const loading = ElLoading.service({
      lock: true,
      text: '注册中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      // 调用注册接口，此时formData中已经包含了头像URL
      await register(formData)
      
      ElMessage.success('注册成功')
      // 注册成功后跳转到登录页
      router.push('/login')
    } finally {
      loading.close()
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '注册失败')
  }
}

// 修改性别选择的值为数字类型
const handleGenderChange = (value) => {
  formData.gender = parseInt(value)
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: #f8f9fa;
}

.register-card {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.register-header h2 {
  font-size: 28px;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.subtitle {
  color: #666;
  margin: 0;
}

.register-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  color: #2c3e50;
  font-size: 14px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-wrapper i {
  position: absolute;
  left: 12px;
  color: #666;
}

.input-wrapper input {
  width: 100%;
  padding: 12px 12px 12px 40px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: all 0.3s;
}

.input-wrapper input:focus {
  border-color: #4CAF50;
  outline: none;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}

.input-wrapper i:last-child {
  left: auto;
  right: 12px;
  cursor: pointer;
}

.gender-options {
  display: flex;
  gap: 20px;
  margin-top: 4px;
}

.gender-option {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.gender-option input[type="radio"] {
  width: 16px;
  height: 16px;
  margin: 0;
}

.avatar-upload {
  position: relative;
  width: 100px;
  height: 100px;
  margin-top: 4px;
}

.avatar-preview, .avatar-placeholder {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #eee;
  position: relative;
}

.avatar-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  background: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-placeholder i {
  font-size: 40px;
  color: #666;
}

.avatar-edit {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background: #4CAF50;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  transition: background 0.3s;
}

.avatar-edit:hover {
  background: #45a049;
}

.avatar-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.agreement {
  margin-top: 10px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.checkbox-label input[type="checkbox"] {
  width: 16px;
  height: 16px;
  margin: 0;
}

.link {
  color: #4CAF50;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

.register-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 14px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 10px;
}

.register-btn:hover:not(:disabled) {
  background: #45a049;
  transform: translateY(-2px);
}

.register-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.login-link a {
  color: #4CAF50;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

@media (max-width: 480px) {
  .register-card {
    padding: 30px 20px;
  }
}
</style> 